import base64
import logging
import os
import shutil
import smtplib
import traceback
from datetime import datetime
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from logging.handlers import RotatingFileHandler

base_dir = os.path.dirname(__file__)


def get_logger():
    # 创建一个 Logger 对象
    logger = logging.getLogger('my_logger')
    logger.setLevel(logging.DEBUG)

    # 创建一个文件处理器
    file_handler = RotatingFileHandler('bisect.log', maxBytes=5 * 1024 * 1024, backupCount=5, encoding='utf-8')
    file_handler.setLevel(logging.DEBUG)

    # 创建一个控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    # 创建一个日志格式
    formatter = logging.Formatter('[%(asctime)s] %(message)s')
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    # 将处理器添加到 Logger
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger


def send_email(subject: str, h2: str = '', body: dict = None):
    try:
        # sender_email = "193391925@qq.com"  # 发件人邮箱
        # sender_password = "fqohvnqlzjqfbhhg"  # 发件人邮箱密码或授权码
        sender_email = "yllikx@isoftstone.com"  # 发件人邮箱
        sender_password = base64.b64decode(b'THlsIzEzNjM2MTA3NjUx').decode('utf-8')  # 发件人邮箱密码或授权码
        receivers_email = ["liyanlin15@huawei.com"]  # 收件人邮箱
        # 创建邮件内容
        subject = subject  # 邮件主题

        # 创建 MIMEMultipart 对象
        msg = MIMEMultipart()
        msg["From"] = sender_email
        msg["To"] = ','.join(receivers_email)
        msg["Subject"] = Header(subject, "utf-8")  # 设置主题编码

        body_str = ''
        if body:
            for testcase, pr in body.items():
                result = '<p>测试用例: {}</p> <p>问题pr: {}</p><br>'.format(testcase, pr)
                body_str += result

        email_content = f"<html><h2>{h2}</h2> <body>{body_str}</body> </html>"
        # 添加邮件正文
        msg.attach(MIMEText(email_content, "html", "utf-8"))  # 使用 HTML 格式

        # 压缩二分报告
        shutil.make_archive(os.path.join(base_dir, 'bisect_report'), 'zip', os.path.join(base_dir, 'bisect_report'))
        attachment_file = os.path.join(base_dir, 'bisect_report.zip')
        # 将报告添加到附件
        with open(attachment_file, 'rb') as attachment:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', f"attachment; filename=bisect_report.zip")
            msg.attach(part)
        # 将日志文件添加到附件
        with open('bisect.log', 'rb') as attachment:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', f"attachment; filename=bisect.log")
            msg.attach(part)

        # 连接 SMTP 服务器,发送邮件
        with smtplib.SMTP_SSL("smtp.isoftstone.com", 465) as server:
            server.login(sender_email, sender_password)  # 登录邮箱
            server.sendmail(sender_email, receivers_email, msg.as_string())  # 发送邮件
            server.quit()
            print("邮件发送成功！")
    except Exception as e:
        print(f"邮件发送失败: {e}")
        print(traceback.format_exc())


def create_bisect_table(testcase, version_list, trigger_list, tag_list, cause_pr):
    """
    生成二分报告
    :param testcase:
    :param version_list:
    :param trigger_list:
    :param tag_list:
    :param cause_pr:
    :return:
    """
    testcase_label = f'<h4>测试用例：{testcase}</h4>'
    pr_label = f'<h4>问题pr：{cause_pr}</h4>'
    # 版本二分表
    v_caption = '<caption>版本二分表</caption>'
    v_th = '<tr><th>序号</th> <th>启动时间</th> <th>镜像链接</th> <th>测试结果</th></tr>'
    v_tds = ''
    for index, trigger in enumerate(version_list):
        buildStartTime = trigger.get('buildStartTime', '')
        buildStartTime = datetime.strptime(buildStartTime, '%Y%m%d%H%M%S').strftime('%Y-%m-%d %H:%M:%S')
        imgObsPath = trigger.get('imgObsPath', '')
        result = trigger.get('result', '')
        if not result:
            td = f'<tr><td>{index + 1}</td> <td>{buildStartTime}</td> <td>{imgObsPath}</td> <td>{result}</td></tr>'
        else:
            if result == 'passed':
                td = f'<tr bgcolor="#00FF00"><td>{index + 1}</td> <td>{buildStartTime}</td> <td>{imgObsPath}</td> <td>{result}</td></tr>'
            elif result == 'crashed':
                td = f'<tr bgcolor="#FFAA00"><td>{index + 1}</td> <td>{buildStartTime}</td> <td>{imgObsPath}</td> <td>{result}</td></tr>'
            else:
                td = f'<tr bgcolor="#FF0000"><td>{index + 1}</td> <td>{buildStartTime}</td> <td>{imgObsPath}</td> <td>{result}</td></tr>'
        v_tds += td
    version_table = f'<table>{v_caption} {v_th} {v_tds}</table>'

    # 调度记录二分表
    tr_caption = '<caption>调度时间二分表</caption>'
    tr_th = '<tr><th>序号</th> <th>调度时间</th> <th>pr</th> <th>镜像链接</th> <th>测试结果</th></tr>'
    tr_tds = ''
    for index, trigger in enumerate(trigger_list):
        trigger_time = trigger.get('trigger_time', '')
        pr = trigger.get('pr', '')
        img_link = trigger.get('img_link', '')
        result = trigger.get('result', '')
        if not result:
            td = f'<tr><td>{index + 1}</td> <td>{trigger_time}</td> <td>{pr}</td> <td>{img_link}</td> <td>{result}</td></tr>'
        else:
            if result == 'passed':
                td = f'<tr bgcolor="#00FF00"><td>{index + 1}</td> <td>{trigger_time}</td> <td>{pr}</td> <td>{img_link}</td> <td>{result}</td></tr>'
            elif result == 'crashed':
                td = f'<tr bgcolor="#FFAA00"><td>{index + 1}</td> <td>{trigger_time}</td> <td>{pr}</td> <td>{img_link}</td> <td>{result}</td></tr>'
            else:
                td = f'<tr bgcolor="#FF0000"><td>{index + 1}</td> <td>{trigger_time}</td> <td>{pr}</td> <td>{img_link}</td> <td>{result}</td></tr>'
        tr_tds += td
    trigger_table = f'<table>{tr_caption} {tr_th} {tr_tds}</table>'

    tg_caption = '<caption>tag二分表</caption>'
    tg_th = '<tr><th>序号</th> <th>镜像构建时间</th> <th>tag发布时间</th> <th>pr</th> <th>镜像链接</th> <th>测试结果</th></tr>'
    tg_tds = ''
    for index, trigger in enumerate(tag_list):
        build_time = trigger.get('build_time', '')
        merge_time = trigger.get('merge_time', '')
        pr = trigger.get('pr', '')
        version_url = trigger.get('version_url', '')
        result = trigger.get('result', '')
        if not result:
            td = f'<tr><td>{index + 1}</td> <td>{build_time}</td> <td>{merge_time}</td> <td>{pr}</td> <td>{version_url}</td> <td>{result}</td></tr>'
        else:
            if result == 'passed':
                td = f'<tr bgcolor="#00FF00"><td>{index + 1}</td> <td>{build_time}</td> <td>{merge_time}</td> <td>{pr}</td> <td>{version_url}</td> <td>{result}</td></tr>'
            elif result == 'crashed':
                td = f'<tr bgcolor="#FFAA00"><td>{index + 1}</td> <td>{build_time}</td> <td>{merge_time}</td> <td>{pr}</td> <td>{version_url}</td> <td>{result}</td></tr>'
            else:
                td = f'<tr bgcolor="#FF0000"><td>{index + 1}</td> <td>{build_time}</td> <td>{merge_time}</td> <td>{pr}</td> <td>{version_url}</td> <td>{result}</td></tr>'
        tg_tds += td
    tag_table = f'<table>{tg_caption} {tg_th} {tg_tds}</table>'

    html = """
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>二分报告</title>
            <style>
                table {
                    width: 100%;
                    border-collapse: collapse; /* 合并边框 */
                }
                th, td {
                    border: 1px solid #000; /* 单元格边框 */
                    padding: 3px; /* 内边距 */
                    text-align: left; /* 文本对齐方式 */
                }
                th {
                    background-color: #f2f2f2; /* 表头背景色 */
                }
            </style>
        </head>
        <body>""" + testcase_label + pr_label + version_table + "<br>" + trigger_table + "<br>" + tag_table + "</body></html>"

    os.makedirs(os.path.join(base_dir, 'bisect_report'), exist_ok=True)
    file_name = os.path.join(base_dir, 'bisect_report', f'{testcase}.html')
    with open(file_name, 'w', encoding='utf-8') as f:
        f.write(html)
